package shop.ynubeggar.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import shop.ynubeggar.model.dataobject.ProductDO;
import shop.ynubeggar.model.valueobject.OrderItemVO;
import shop.ynubeggar.request.ConfirmOrderRequest;
import shop.ynubeggar.service.PointChangeService;
import shop.ynubeggar.service.ProductOrderItemService;
import shop.ynubeggar.service.ProductOrderService;
import shop.ynubeggar.service.ProductService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiuQ
 * @since 2022-09-22
 */
@Api(tags = "订单")
@RestController
@RequestMapping("/api/order/v1")
public class ProductOrderController {

    @Resource
    ProductOrderService productOrderService;
    @Resource
    ProductOrderItemService productOrderItemService;
    @Resource
    ProductService productService;
    @Resource
    PointChangeService pointChangeService;

    @ApiOperation(value = "新订单")
    @PostMapping("/")
    public void confirmOrder(@ApiParam("订单信息") @RequestBody ConfirmOrderRequest confirmOrderRequest, HttpServletResponse response) {
//        创建订单对象
        Long orderId = productOrderService.createOrder(confirmOrderRequest);
        pointChangeService.reduce(confirmOrderRequest.getPayAmount().intValue());
//        更新购物车
//        cartService.updateCart(confirmOrderRequest.getProductIdAndNums());
//        锁定库存
        List<ProductDO> productDOList = productService.lockStock(confirmOrderRequest);
//        创建子订单对象
        productOrderItemService.createOrderItem(orderId, confirmOrderRequest, productDOList);
    }

    @ApiOperation(value = "所有订单")
    @GetMapping("/")
    public Object listAllOrder(
            @ApiParam(value = "id") @RequestParam(value = "id", defaultValue = "-1") long id,
            @ApiParam(value = "当前页") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam(value = "每页显示条数") @RequestParam(value = "size", defaultValue = "10") int size) {
        if (id > 0) {
            return productOrderService.findOne(id);
        } else {
            return productOrderService.listAll(page, size);
        }
    }

    @ApiOperation(value = "所有订单细项")
    @GetMapping("/detail/{id}")
    public List<OrderItemVO> listOrderItems(@ApiParam(value = "id") @PathVariable(value = "id") long id) {
        return productOrderItemService.listAllItems(id);
    }
}

